import 'package:bigegg/common/log/xmm_logcat.dart';
import 'package:bigegg/entity/xmm_oss_policy.dart';
import 'package:bigegg/entity/xmm_video_info.dart';
import 'package:bigegg/global/user/xmm_account_manager.dart';
import 'package:bigegg/utils/xmm_date_utils.dart';
import 'package:bigegg/utils/xmm_platform_utils.dart';
import 'package:dio/dio.dart';

import '../../common/error/xmm_exception.dart';
import '../../common/http/xmm_http.dart';
import '../../common/http/xmm_response_data.dart';
import '../../entity/user/xmm_app_config.dart';
import '../../entity/user/xmm_block_user.dart';
import '../../entity/user/xmm_login.dart';
import '../../entity/user/xmm_strategy.dart';
import '../../entity/user/xmm_user.dart';
import '../../entity/user/xmm_wall_user.dart';
import '../../entity/xmm_coin_goods.dart';
import '../../global/xmm_apis.dart';

class XmmRemoteRepository {
  Future<XmmLogin> oauth(int oauthType, String token) async {
    FormData formData = FormData.fromMap({
      "oauthType": oauthType,
      "token": token,
    });
    var data = await XmmXHttpClient.instance().post(
      XmmApis.oauth,
      formData: formData,
    );
    return XmmLogin.fromJson(data);
  }

  Future<dynamic> logout() async {
    return await XmmXHttpClient.instance().post(XmmApis.logout);
  }

  Future<dynamic> deleteAccount() async {
    return await XmmXHttpClient.instance().post(XmmApis.deleteAccount);
  }

  Future<dynamic> isValidToken(String token) async {
    var params = XmmXHttpClient.instance().createParams();
    params["token"] = token;
    return await XmmXHttpClient.instance()
        .post(XmmApis.isValidToken, params: params);
  }

  Future<XmmStrategy> getStrategy() async {
    var data = await XmmXHttpClient.instance().get(XmmApis.getStrategy);
    return XmmStrategy.fromJson(data);
  }

  Future<XmmAppConfig> getConfigInfo(String ver) async {
    var params = XmmXHttpClient.instance().createParams();
    params["ver"] = ver;
    var data = await XmmXHttpClient.instance().get(
      XmmApis.getConfig,
      params: params,
    );
    return XmmAppConfig.fromJson(data);
  }

  Future<String> getRongCloudToken() async {
    var params = XmmXHttpClient.instance().createParams();
    var data = await XmmXHttpClient.instance()
        .get(XmmApis.getRongCloudToken, params: params);
    return data;
  }

  Future<List<XmmWallUser>> wallSearch() async {
    var params = XmmXHttpClient.instance().createParams();
    params["category"] = "Popular"; // 分类固定传Popular
    params["isPageMode"] = true;
    params["isRemoteImageUrl"] = true; // 必须为true 否则返回的头像链接需要拼接
    params["limit"] = 20;
    params["page"] = 1;
    params["tag"] = "All";
    var data = await XmmXHttpClient.instance()
        .post(XmmApis.wallSearch, params: params);
    var wallUserList = <XmmWallUser>[];
    for (var item in data) {
      XmmWallUser wallUser = XmmWallUser.fromJson(item);
      wallUserList.add(wallUser);
    }
    return wallUserList;
  }

  Future<List<XmmUser>> getFollowList() async {
    var params = XmmXHttpClient.instance().createParams();
    params["limit"] = 20;
    params["page"] = 1;
    var data = await XmmXHttpClient.instance()
        .post(XmmApis.getFriendsListPage, params: params);
    var userList = <XmmUser>[];
    for (var item in data) {
      XmmUser wallUser = XmmUser.fromJson(item);
      userList.add(wallUser);
    }
    return userList;
  }

  Future<List<XmmBlockUser>> getBlackList() async {
    var params = XmmXHttpClient.instance().createParams();
    var data = await XmmXHttpClient.instance().post(
      XmmApis.blockList,
      params: params,
    );
    var userList = <XmmBlockUser>[];
    for (var item in data) {
      XmmBlockUser wallUser = XmmBlockUser.fromJson(item);
      userList.add(wallUser);
    }
    return userList;
  }

  Future<XmmResponseData> follow(String userId) async {
    var params = XmmXHttpClient.instance().createParams();
    params["followUserId"] = userId;
    var data = await XmmXHttpClient.instance().postResponse(
      XmmApis.addFriend,
      params: params,
    );
    return data;
  }

  Future<XmmResponseData> unfollow(String userId) async {
    var params = XmmXHttpClient.instance().createParams();
    params["followUserId"] = userId;
    var data = await XmmXHttpClient.instance().postResponse(
      XmmApis.unfriend,
      params: params,
    );
    return data;
  }

  Future<XmmResponseData> black(String userId) async {
    var params = XmmXHttpClient.instance().createParams();
    params["broadcasterId"] = userId;
    params["complainCategory"] = "Block";
    var data = await XmmXHttpClient.instance()
        .postResponse(XmmApis.insertRecord, params: params);
    return data;
  }

  Future<XmmResponseData> removeBlack(String userId) async {
    var params = XmmXHttpClient.instance().createParams();
    params["blockUserId"] = userId;
    var data = await XmmXHttpClient.instance()
        .postResponse(XmmApis.removeBlock, params: params);
    return data;
  }

  Future<XmmResponseData> report(String userId, String reportType) async {
    var params = XmmXHttpClient.instance().createParams();
    params["broadcasterId"] = userId;
    params["complainCategory"] = "Report";
    params["complainSub"] = reportType;
    var data = await XmmXHttpClient.instance()
        .postResponse(XmmApis.insertRecord, params: params);
    return data;
  }

  Future<XmmResponseData> consumeCoin(int outlay) async {
    var params = XmmXHttpClient.instance().createParams();
    params["outlay"] = outlay;
    params["source"] = "iap";
    var data = await XmmXHttpClient.instance()
        .postResponse(XmmApis.reviewModeConsume, params: params);
    return data;
  }

  Future<XmmOssPolicy> getOssPolicy() async {
    var params = XmmXHttpClient.instance().createParams();
    var data =
        await XmmXHttpClient.instance().get(XmmApis.ossPolicy, params: params);
    return XmmOssPolicy.fromJson(data);
  }

  Future<String> updateUserAvatar(String localPath) async {
    XmmOssPolicy ossPolicy = await getOssPolicy();
    DateTime dateTime = DateTime.now();
    String fileName = localPath.split('/').last;
    String format = fileName.split('.').last;
    int imageTimeName = dateTime.millisecondsSinceEpoch +
        (dateTime.microsecondsSinceEpoch ~/ 1000000);
    String imageName = '$imageTimeName.$format';
    String host = ossPolicy.host ?? "";
    String dir = ossPolicy.dir ?? "";
    var filePath = await MultipartFile.fromFile(localPath, filename: fileName);
    final formData = FormData.fromMap({
      'ossaccessKeyId': ossPolicy.accessKeyId,
      'policy': ossPolicy.policy,
      'signature': ossPolicy.signature,
      'callback': ossPolicy.callback,
      'key': '$dir/$imageName',
      'file': filePath,
    });
    var data = await XmmXHttpClient.instance().post(host, formData: formData);
    var filename = data["filename"];
    if (filename != null) {
      var params = XmmXHttpClient.instance().createParams();
      params["avatarPath"] = filename;
      var resp = await XmmXHttpClient.instance()
          .post(XmmApis.updateAvatar, params: params);
      return resp["thumbUrl"];
    }
    return Future.error(XmmErrorException("filename is null"));
  }

  Future<dynamic> updateUserInfo(String nickname, DateTime birthday) async {
    var params = XmmXHttpClient.instance().createParams();
    params["nickname"] = nickname;
    params["birthday"] = XmmDateUtils.parseTimeYYMMDD(birthday);
    var data = await XmmXHttpClient.instance()
        .post(XmmApis.saveUserInfo, params: params);
    return data;
  }

  Future<XmmWallUser> getUserInfo(String userId) async {
    var params = XmmXHttpClient.instance().createParams();
    params["userId"] = userId;
    var data = await XmmXHttpClient.instance()
        .get(XmmApis.getUserInfo, params: params);
    return XmmWallUser.fromJson(data);
  }

  Future<List<XmmCoinGoods>> getCoinGoodsList() async {
    var params = XmmXHttpClient.instance().createParams();
    params["isIncludeSubscription"] = false;
    params["payChannel"] = "IAP";
    var data = await XmmXHttpClient.instance()
        .post(XmmApis.coinGoodsSearch, params: params);
    var coinGoodsList = <XmmCoinGoods>[];
    for (var item in data) {
      XmmCoinGoods coinGoods = XmmCoinGoods.fromJson(item);
      coinGoodsList.add(coinGoods);
    }
    return coinGoodsList;
  }

  Future<XmmResponseData> createCoinRecharge(String goodsCode) async {
    var params = XmmXHttpClient.instance().createParams();
    params["payChannel"] = "IAP";
    params["entry"] = "";
    params["source"] = "";
    params["goodsCode"] = goodsCode;
    var data = await XmmXHttpClient.instance()
        .postResponse(XmmApis.coinRechargeCreate, params: params);
    return data;
  }

  Future<XmmResponseData> coinRechargePayment(
      String orderNo, String payload, String transactionId) async {
    var params = XmmXHttpClient.instance().createParams();
    params["type"] = 1;
    params["orderNo"] = orderNo; ////支付订单号,创建订单返回的订单号
    params["payload"] = payload; //支付有效载荷,苹果返回的购买凭证
    params["transactionId"] = transactionId; //内购交易号苹果返回的交易流水号
    var data = await XmmXHttpClient.instance()
        .postResponse(XmmApis.coinRechargePayment, params: params);
    return data;
  }

  Future<String> translate(String content) async {
    var params = XmmXHttpClient.instance().createParams();
    params["key"] = XmmAccountManager.instance.appConfig?.getTranslationKey();
    params["target"] = XmmPlatformUtils.systemLanguage;
    params["q"] = content;
    params["format"] = "text";
    var data = await XmmXHttpClient.instance()
        .postResponse(XmmApis.translate, params: params);
    return data.data['data']['translations'][0]['translatedText'];
  }

  Future<List<XmmVideoInfo>> getVideoList() async {
    var data = await XmmXHttpClient.instance()
        .post(XmmApis.shortLinkMediaSearch, formData: videoListFormData);
    var videoInfoList = <XmmVideoInfo>[];
    for (var item in data) {
      XmmVideoInfo coinGoods = XmmVideoInfo.fromJson(item);
      videoInfoList.add(coinGoods);
    }
    return videoInfoList;
  }

  var videoListFormData = [
    {"mediaPath": "aface/lanlin/RallyRound/video/1.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/2.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/3.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/4.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/5.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/6.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/7.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/8.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/9.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/10.mp4", "mediaType": "video"},
    {"mediaPath": "aface/lanlin/RallyRound/video/11.mp4", "mediaType": "video"}
  ];
}
